package com.jefe.bamboo;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.GenericPortlet;
import javax.portlet.ActionRequest;
import javax.portlet.RenderRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import javax.portlet.PortletException;
import java.io.IOException;
import java.net.URLEncoder;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.ValidatorException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.jefe.bamboo.service.model.*;
import com.jefe.bamboo.service.service.*;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;

/**
 *
 * @author Sonali Mendis
 * Bamboo Portlet for Jefe (http://www.jefesolutions.com)
 * GNU License
 */
public class Bamboo extends GenericPortlet {

    public void processAction(ActionRequest request, ActionResponse response) throws PortletException,IOException {

        String error = null;
        String success = null;

        if(request.getPortletMode().equals(PortletMode.EDIT)){
            boolean editOk = false;
            //get form submitted data
            String host = request.getParameter("formHost");
            String portStr = request.getParameter("formPort");
            if(portStr==null||portStr.equals("")){
                portStr = "0";
            }
            int port = Integer.parseInt(portStr);
            String username = request.getParameter("formUser");
            String password = request.getParameter("formPass");
            //get current user id from Liferay
            long id = 0;
            User currentUser = null;
            try {
                currentUser = PortalUtil.getUser(request);
                id = currentUser.getUserId();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //check whether user is already available
            Boolean existance = false;
            UserPrefsBmb user;
            try{
                //user exists => only update the details
                user = UserPrefsBmbLocalServiceUtil.getUserPrefsBmb(id);
                existance = true;
            }catch(Exception ex){
                // create the new entry
                System.out.println("User is not currently in the database"+ ex.getMessage());

                int count = 0;
                try{
                    count = UserPrefsBmbLocalServiceUtil.getUserPrefsBmbsCount();
                }catch(Exception eex){
                    System.out.println("Can not read the database entry count"+eex.getMessage());
                }
                count = count +1;
                user = UserPrefsBmbLocalServiceUtil.createUserPrefsBmb(count);
                System.out.println("Table is created..");
            }
            //set data
            user.setBmbId(id);
            user.setBmbHost(host);
            user.setBmbPort(port);
            user.setBmbUser(username);
            user.setBmbPass(password);
            //commit to the database
            try {
                if(existance){
                    UserPrefsBmbLocalServiceUtil.updateUserPrefsBmb(user);
                    System.out.println("User details updated");
                }else{
                    UserPrefsBmbLocalServiceUtil.addUserPrefsBmb(user);
                    System.out.println("User is added");
                }
                editOk = true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if(editOk){
                success = "Successfully stored the preferences.";
                response.setRenderParameter("success", URLEncoder.encode(success, "UTF-8"));
            }else{
                error = "Unsuccessful in storing the preferences";
                response.setRenderParameter("error", URLEncoder.encode(error, "UTF-8"));
            }
        }
        if(request.getPortletMode().equals(PortletMode.VIEW)){
            String edit = request.getParameter("edit");
            if(edit.equals("link")){
                response.setPortletMode(PortletMode.EDIT);
            }else{
                String filter = request.getParameter("vformFilter");
                response.setRenderParameter("filter", filter); //send filter parameter to doView();
            }
        }
    }
    
    public void doView(RenderRequest request,RenderResponse response) throws PortletException,IOException {
        response.setContentType("text/html");
        //get user id from Liferay
        long id = 0;
        User currentUser = null;
        try {
            currentUser = PortalUtil.getUser(request);
            id = currentUser.getUserId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        UserPrefsBmb userDtl;
        String host = null;
        int port = 0;
        String user = null;
        String pass = null;
        String fil = null;
        Boolean userSet = false;
        //if user is already in the database => get user information
        try {
            userDtl = UserPrefsBmbLocalServiceUtil.getUserPrefsBmb(id);
            host = userDtl.getBmbHost();
            port = userDtl.getBmbPort();
            user = userDtl.getBmbUser();
            pass = userDtl.getBmbPass();
            fil = request.getParameter("filter");
            userSet = true;
            
        } catch (Exception ex) {
            System.out.println("User Preferences are not set. Please set the preferences to proceed.");
        }
        
        if (userSet) {  //user is in the database, user data successfully retrieved.
            //do filter value correction
            if(fil==null||fil.equals("null")||fil.equals("")){
                fil = "*";
            }
            //call user's bamboo data
            Driver projList = new Driver();
            try {
                request.setAttribute("projList", projList.setProject(host, port, fil, user, pass));
            } catch (SAXException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            }
            request.setAttribute("error", projList.getErrors());
        } else {
            //this is the first time
        }
        PortletRequestDispatcher dispatcher =
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/Bamboo_view.jsp");
        dispatcher.include(request, response);
    }
    public void doEdit(RenderRequest request,RenderResponse response) throws PortletException,IOException {
            response.setContentType("text/html");   
        PortletRequestDispatcher dispatcher =
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/Bamboo_edit.jsp");
        dispatcher.include(request, response);
    }
    public void doHelp(RenderRequest request, RenderResponse response) throws PortletException,IOException {

        response.setContentType("text/html");        
        PortletRequestDispatcher dispatcher =
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/Bamboo_help.jsp");
        dispatcher.include(request, response);
    }
}